<script type="text/javascript">
var normal_list_init_success = false;
var fake_deleted_list_init_success = false;
$(document).ready(function() {
    $.extend({
        refresh_volume_list: function() {
            if ($('#interval_tip').hasClass("volume_list")) {
                $("#volume_available_tb").trigger("reloadGrid");
            }
        }
    });

    if (window.interval_volume_list) {} else {
        window.interval_volume_list = window.setInterval("$.refresh_volume_list()", 300000);
    }

    var initial_width;

    //初始化完成
    
    initNormalTable();

    function get_used(ids) {
        ids_str = ids.join(',')
        $.get('/volume/get_used', {
            'ids': ids_str
        }, function(data) {
            for (var i = 0; i < ids.length; i++) {
                $('#volume_available_tb').jqGrid('setRowData', ids[i], {
                    used: data[i]
                });
            }
        });

    }
    //daiwenxue-update
    $("#volume_create_button").click(function() {
        angular.element('#volume_controller').scope().open("/volume/create");

    });

    $(".title-tag ul li").on('click', function() { 
        $(this).siblings().removeClass('active');
        $(this).addClass('active');
        var tid = $(this).attr('tid');
        if (tid == '#normal_list') {
            $('#fake_deleted_list').hide();
            $("#normal_list").show();
            if(normal_list_init_success) {
                $("#volume_available_tb").trigger('reloadGrid');
            }
            initNormalTable();
        } else {
            $("#normal_list").hide();
            $('#fake_deleted_list').show();
            if(fake_deleted_list_init_success) {
                $("#volume_fake_deleted_list").trigger('reloadGrid');
            } else {
                initFakeDeletedTable();
            }
        }
    });
});

function getNormalCount () {
    $.ajax({
        url:'volume/grid',
        data:{
            fake_deleted:false,
            rows:10,
            page:1,
            sidx:'id',
            sord:'desc'
        },
        type:'post',
        dataType:'json',
        success:function(data) {
            $('#normal_count').text(data.records);
        }
    });
}

function getFakeDeletedCount () {
    $.ajax({
        url:'volume/grid',
        data:{
            fake_deleted:true,
            rows:10,
            page:1,
            sidx:'id',
            sord:'desc'
        },
        type:'post',
        dataType:'json',
        success:function(data) {
            $('#fake_deleted_count').text(data.records);
        }
    });
}

function initNormalTable () {
    $('#volume_available_tb').jqGrid({
        url: '/volume/grid',
        datatype: 'json',
        mtype: 'POST',
        postData: {
            fake_deleted: false
        },
        colNames: ['编号', '[["label path"|translate]]', 'IQN', '[["label Protocol type"|translate]]', "路径",
            'STAT', '[["label state"|translate]]', '[["label Disk configuration"|translate]]',
            '[["label size"|translate]](G)', '[["label been used"|translate]](G)', 'IOPS', '吞吐(MB/s)',
            '客户端连接', "[[ 'PROTECTION DOMAINS'|translate ]]", "[['home Consistency group'|translate]]",
            'CloneType', '来自快照', 'SnapshotID', 'Latency监控', '分层',
            "[['label owner'|translate]]", '[["label Creation time"|translate]]', '[["label operation"|translate]]',
        ],
        colModel: [{
            name: 'id',
            index: 'id',
            width: 3,
            align: 'left',
            hidden: true
        }, {
            name: 'name',
            index: 'name',
            width: 5,
            align: 'left',
            formatter: function(cellvalue, option, row) {
                var outerWidth = $('#volume_available_tb_name').width() - 20;
                return '<a style="display:inline-block;text-overflow:ellipsis; white-space:nowrap;overflow:hidden;width:' + outerWidth + 'px;" href="#" onclick="detail_open(\'' + option.gid + '\',\'' + option.rowId + '\')">' + cellvalue + '</a>';
            },
            unformat: function(cellvalue) {
                return cellvalue;
            }
        }, {
            name: 'volume_IQN',
            index: 'volume_IQN',
            width: 7,
            align: 'left',
            sortable: false,
            formatter:function(cellvalue,option,row) {
                if(cellvalue == '') {
                    return "N/A"
                } else {
                    var html = '';
                    var width = $("#volume_available_tb_volume_IQN").width()-20;
                    html += '<span class="td_volume_iqn" style="display:inline-block;text-overflow:ellipsis; white-space:nowrap;overflow:hidden;width:' + width + 'px;">' + cellvalue + '</span>';
                    return html;
                }
            },unformat:function(cellvalue) {
                return cellvalue;
            }
        }, {
            name: 'protocol',
            index: 'protocol',
            width: 5,
            align: 'left',
            sortable: false
        }, {
            name: 'lun_path',
            index: 'lun_path',
            width: 5,
            align: 'left',
            hidden: true
        }, {
            name: 'status',
            index: 'status',
            width: 6,
            align: 'left',
            hidden: true
        }, {
            name: 'status_',
            index: 'status_',
            width: 3,
            align: 'left'
        }, {
            name: 'provisioning_',
            tatus_ndex: 'provisioning_',
            width: 5,
            align: 'left',
            sortable: false
        }, {
            name: 'size_gb',
            index: 'size_gb',
            width: 5,
            align: 'left'
        }, {
            name: 'used',
            index: 'used',
            width: 5,
            align: 'left',
            sortable: false
        }, {
            name: 'IPOS',
            index: 'IPOS',
            width: 8,
            align: 'left',
            sortable: false,
        }, {
            name: 'swallow',
            index: 'swallow',
            width: 8,
            align: 'left',
            sortable: false
        }, {
            name: 'connection',
            index: 'connection',
            width: 8,
            align: 'left',
            sortable: false,
            hidden: true
        }, {
            name: 'protection_domain',
            index: 'protection_domain',
            width: 6,
            align: 'left',
            hidden: true
        }, {
            name: 'vgroup',
            index: 'vgroup',
            width: 5,
            align: 'left'   
        }, {
            name: 'clone_type',
            index: 'clone_type',
            width: 5,
            align: 'left',
            hidden: true
        }, {
            name: 'fromsnap',
            index: 'fromsnap',
            width: 5,
            align: 'left',
            formatter: function(cell,option,row) {
                var html = makeEllipsis(cell,option,'span');
                return html;
            },unformat:function(cell) {
                return cell;
            }
        }, {
            name: 'snapshot_id',
            index: 'snapshot_id',
            width: 5,
            align: 'left',
            hidden: true
        }, {
            name: 'analysis_latency',
            index: 'analysis_latency',
            width: 7,
            align: 'left'
        }, {
            name: 'priority_',
            index: 'priority_',
            width: 6,
            align: 'left'
        }, {
            name: 'username',
            index: 'username',
            width: 6,
            align: 'left'
        }, {
            name: 'created_at',
            index: 'created_at',
            width: 10,
            align: 'left',
            hidden: true
        }, {
            name: 'service',
            index: 'service',
            width: 20,
            align: 'left',
            sortable: false,
            detailHidden:true,
            formatter:function(cell, option, row) {
                row = row2object(row, option.gid);
                var row_id = row['id']
                var row_name = row['name']
                var row_iqn = row['volume_IQN']
                var html = '';

                html += '<button title="创建快照" class="btn btn-blue btn-sm" ' 
                    + (row['status'] == 'normal' ? '' : 'disabled') 
                    + ' onclick=volume_create_snapshot(' + row_id + ')>创建快照</button>';

                html += '<button style="margin-left:10px;" title="编辑" class="btn btn-blue btn-sm" '
                    + (row['status'] == 'normal' ? '' : 'disabled') 
                    +' onclick=volume_update(' + row_id + ')>编辑</button>';

                var row_show_name = '';
                if(row_iqn == '' || row_iqn == 'N/A') {
                    var row_show_name = row_name
                } else {
                    var row_show_name = row_iqn
                }
                html += '<button style="margin-left:10px;" title="删除" class="btn btn-blue btn-sm" onclick=confirm_volume_delete(' + row_id + ',"' + row_show_name + '")>删除</button>';

                console.log(row['status'] == 'normal' ? '' : 'disabled')
                html += '<button style="margin-left:10px;" title="卷拷贝" class="btn btn-blue btn-sm" ' + (row['status'] == 'normal' ? '' : 'disabled') + ' onclick=volume_copy(' + row_id + ')>卷拷贝</button>';
                return html;
            }
        }],
        page: 1,
        rowNum: 10,
        sortname: 'id',
        sortorder: 'desc',
        viewrecords: true,
        altclass: 'ui-priority-secondary',
        altRows: true,
        autowidth: true,
        shrinkToFit: true,
        beforeSelectRow:function(rowid, e) {
            if($(e.target).is('input')) {
                return true;
            }
            return false;
        },
        gridComplete: function() {
            var gridData = $(this).jqGrid('getRowData');
            jqgrid_page($(this), gridData);
            jqgrid_resize($(this));
            getNormalCount();
            getFakeDeletedCount();
            normal_list_init_success = true;
        },
        resizeStart: function() {
            initial_width = $(this).width();
        },
        resizeStop: function() {
            $(this).width(initial_width);
            $(".ui-jqgrid-hbox").find('.ui-jqgrid-htable').width(initial_width);
            var ids = $(this).jqGrid('getDataIDs');
            for (var i = 0; i < ids.length; i++) {
                volume_IQN = $(this).getCell(ids[i], "volume_IQN");
                iqn_td_width = $("#volume_available_tb_volume_IQN").width();
                $(".td_volume_iqn").width(iqn_td_width);
            }
        }
    });
}

function initFakeDeletedTable() {
    $('#volume_fake_deleted_list').jqGrid({
        url: '/volume/grid',
        datatype: 'json',
        mtype: 'POST',
        postData: {
            fake_deleted: true
        },
        colNames: ['编号', '路径', 'IQN', '协议类型', "路径",
            'STAT', '状态', '磁盘配置',
            '大小(G)', '已用(G)', 'IOPS', '吞吐(MB/s)',
            '客户端连接', "[[ 'PROTECTION DOMAINS'|translate ]]", "卷组",
            'CloneType', '来自快照', 'SnapshotID', 'Latency监控', '分层',
            "所有者", '[["label Creation time"|translate]]', '操作',
        ],
        colModel: [{
            name: 'id',
            index: 'id',
            width: 3,
            align: 'left',
            hidden: true
        }, {
            name: 'name',
            index: 'name',
            width: 5,
            align: 'left',
            formatter: function(cellvalue, option, row) {
                var outerWidth = $('#volume_available_tb_name').width() - 20;
                return '<a style="display:inline-block;text-overflow:ellipsis; white-space:nowrap;overflow:hidden;width:' + outerWidth + 'px;" href="#" onclick="detail_open(\'' + option.gid + '\',\'' + option.rowId + '\')">' + cellvalue + '</a>';
            },
            unformat: function(cellvalue) {
                return cellvalue;
            }
        }, {
            name: 'volume_IQN',
            index: 'volume_IQN',
            width: 7,
            align: 'left',
            sortable: false,
            formatter:function(cellvalue,option,row) {
                if(cellvalue == '') {
                    return "N/A"
                } else {
                    var html = '';
                    var width = $("#volume_available_tb_volume_IQN").width()-20;
                    html += '<span class="td_volume_iqn" style="display:inline-block;text-overflow:ellipsis; white-space:nowrap;overflow:hidden;width:' + width + 'px;">' + cellvalue + '</span>';
                    return html;
                }
            },unformat:function(cellvalue) {
                return cellvalue;
            }
        }, {
            name: 'protocol',
            index: 'protocol',
            width: 5,
            align: 'left',
            sortable: false
        }, {
            name: 'lun_path',
            index: 'lun_path',
            width: 5,
            align: 'left',
            hidden: true
        }, {
            name: 'status',
            index: 'status',
            width: 6,
            align: 'left',
            hidden: true
        }, {
            name: 'status_',
            index: 'status_',
            width: 3,
            align: 'left'
        }, {
            name: 'provisioning_',
            tatus_ndex: 'provisioning_',
            width: 5,
            align: 'left',
            sortable: false
        }, {
            name: 'size_gb',
            index: 'size_gb',
            width: 5,
            align: 'left'
        }, {
            name: 'used',
            index: 'used',
            width: 5,
            align: 'left',
            sortable: false
        }, {
            name: 'IPOS',
            index: 'IPOS',
            width: 8,
            align: 'left',
            sortable: false,
        }, {
            name: 'swallow',
            index: 'swallow',
            width: 8,
            align: 'left',
            sortable: false
        }, {
            name: 'connection',
            index: 'connection',
            width: 8,
            align: 'left',
            sortable: false,
            hidden: true
        }, {
            name: 'protection_domain',
            index: 'protection_domain',
            width: 6,
            align: 'left',
            hidden: true
        }, {
            name: 'vgroup',
            index: 'vgroup',
            width: 5,
            align: 'left'   
        }, {
            name: 'clone_type',
            index: 'clone_type',
            width: 5,
            align: 'left',
            hidden: true
        }, {
            name: 'fromsnap',
            index: 'fromsnap',
            width: 5,
            align: 'left',
            formatter: function(cell,option,row) {
                var html = makeEllipsis(cell,option,'span');
                return html;
            },unformat:function(cell) {
                return cell;
            }
        }, {
            name: 'snapshot_id',
            index: 'snapshot_id',
            width: 5,
            align: 'left',
            hidden: true
        }, {
            name: 'analysis_latency',
            index: 'analysis_latency',
            width: 7,
            align: 'left'
        }, {
            name: 'priority_',
            index: 'priority_',
            width: 6,
            align: 'left'
        }, {
            name: 'username',
            index: 'username',
            width: 6,
            align: 'left'
        }, {
            name: 'created_at',
            index: 'created_at',
            width: 10,
            align: 'left',
            hidden: true
        }, {
            name: 'service',
            index: 'service',
            width: 20,
            align: 'left',
            sortable: false,
            detailHidden:true,
            formatter:function(cell, option, row) {
                row = row2object(row, option.gid);
                var row_id = row['id']
                var row_name = row['name']
                var row_iqn = row['volume_IQN']
                var html = '';
                var row_show_name = '';
                if(row_iqn == '' || row_iqn == 'N/A') {
                    var row_show_name = row_name;
                } else {
                    var row_show_name = row_iqn;
                }
                html += '<button title="彻底删除" class="btn btn-blue btn-sm" onclick=confirm_volume_expunge(' + row_id + ',"' + row_show_name + '")>彻底删除</button>';
                html += '<button style="margin-left:10px;" title="恢复卷" class="btn btn-blue btn-sm" onclick=confirm_volume_restore(' + row_id + ',"' + row_show_name + '")>恢复卷</button>'
                return html;
            }
        }],
        page: 1,
        rowNum: 10,
        sortname: 'id',
        sortorder: 'desc',
        viewrecords: true,
        altclass: 'ui-priority-secondary',
        altRows: true,
        autowidth: true,
        shrinkToFit: true,
        beforeSelectRow:function(rowid, e) {
            if($(e.target).is('input')) {
                return true;
            }
            return false;
        },
        gridComplete: function() {
            var gridData = $(this).jqGrid('getRowData');
            jqgrid_page($(this), gridData);
            jqgrid_resize($(this));
            getNormalCount();
            getFakeDeletedCount();
            fake_deleted_list_init_success = true;
        },
        resizeStart: function() {
            initial_width = $(this).width();
        },
        resizeStop: function() {
            $(this).width(initial_width);
            $(".ui-jqgrid-hbox").find('.ui-jqgrid-htable').width(initial_width);
            var ids = $(this).jqGrid('getDataIDs');
            for (var i = 0; i < ids.length; i++) {
                volume_IQN = $(this).getCell(ids[i], "volume_IQN");
                iqn_td_width = $("#volume_available_tb_volume_IQN").width();
                $(".td_volume_iqn").width(iqn_td_width);
            }
        }
    });
}

function from_clone_snapshot_click(snapshot_id) {
    $("#logo_snapshot").click();
    $("#logo_snapshot_list").click();
    $("#snapshot_table").jqGrid('setGridParam', {
        page: 1,
        url: '/grid_snapshot?id=' + snapshot_id
    }).trigger('reloadGrid');
}

function volume_create_snapshot(volume_id) {
    angular.element('#snapshot_create').scope().open("/snapshot_create?id=" + volume_id);
}
function volume_copy(volume_id) {
    angular.element('#volume_controller').scope().open("/volume/copy?id=" + volume_id);
}

function volume_flatten(volume_id) {
    var url = "/volume/flatten";
    volume_ajax(url, volume_id);
}

function volume_delete(volume_id) {
    var url = "/volume/delete";
    volume_ajax(url, volume_id);
}

function volume_expunge(volume_id) {
    var url = "/volume/expunge";
    volume_ajax(url, volume_id, 'volume_fake_deleted_list');
}

function volume_restore(volume_id) {
    var url = "/volume/restore";
    volume_ajax(url, volume_id, 'volume_fake_deleted_list');
}

function volume_ajax(url, volume_id, table_id) {
    $.ajax({
        url: url,
        type: "GET",
        dataType: "json",
        data: {
            'id': volume_id
        },
        success: function(data) {
            if (data.reply.is_success) {
                if(!table_id) {
                    table_id = 'volume_available_tb';
                }
                $("#" + table_id).trigger("reloadGrid");
            } else {
                error = data.reply.error;
                SelfAlert(error);
            }
            $('#tb_event_mng').trigger("reloadGrid");
        }
    });
}

var d = new Array(); 
{% for pool in pools %}
var values = new Array();
values[0] = "{{pool.id}}"
values[1] = "{{pool.name}}"
d.push(values) 
{% endfor %}

var values = new Array();
values[0] = "all"
values[1] = ""
d.push(values)
$('#volume_tg').rqDropDown({
    "datatype": "local",
    "source": d,
    "onchange": "select_tg"
});

function select_tg(tg, id) {
    $("#volume_available_tb").jqGrid('setGridParam', {
        page: 1,
        url: '/volume/grid?t_id=' + id
    }).trigger('reloadGrid');
}

function confirm_volume_restore(volume_id, volume_name) {
    msg = '确定要恢复卷（'+ volume_name +'）吗？';
    SelfConfirm(msg, volume_restore, volume_id, "恢复卷");
}

function confirm_volume_expunge(volume_id, volume_name) {
    msg = '确定彻底删除卷（' + volume_name + '）吗？';
    SelfConfirm(msg, volume_expunge, volume_id, "删除提示");
}

function confirm_volume_delete(volume_id, volume_name) {
    msg = '删除卷的容量需要逐步释放,确定删除卷（' + volume_name + '）？';
    SelfConfirm(msg, volume_delete, volume_id, "删除提示");
}

function confirm_volume_flatten(volume_id, volume_name) {
    msg = 'Flatten操作可时该克隆卷与来源快照完成真正的脱离,确定操作（' + volume_name + '）？';
    SelfConfirm(msg, volume_flatten, volume_id, "Flatten");
}


function volume_update(volume_id) {
    angular.element('#volume_controller').scope().open('/volume/update?id=' + volume_id);
}

function select_protocols(tg, id) {
    $("#volume_available_tb").jqGrid('setGridParam', {
        page: 1,
        url: '/volume/grid?protocol=' + id
    }).trigger('reloadGrid');
}

var protocols_source = [
    ['', '全部']
]; 
{% for protocol in protocols %}
var values = new Array();
var protocol = "{{ protocol }}".toUpperCase();
if (protocol == 'ISCSI') {
    protocol = "iSCSI";
}
values[0] = "{{ protocol }}";
values[1] = protocol;
protocols_source.push(values) 
{% endfor %}

$('#volume_protocol_search').rqDropDown({
    "datatype": "local",
    "source": protocols_source,
    "onchange": "select_protocols"
});

</script>
<div class="panel panel-f-style">
    <div class="panel-body">
        <div class="title-tag">
             <h3>卷</h3>
            <p>卷管理</p>
            <div style="height: 25px"></div>
            <ul>
                <li class="active" tid="#normal_list">正常卷(<b id="normal_count"></b>)</li>
                <li tid="#fake_deleted_list">已删除卷(<b id="fake_deleted_count"></b>)</li>
            </ul>
        </div>
        <div id="normal_list">
            <div class="grid-tools">
                <div class="grid-operate pull-left">
                    <button id="snapshot_create" ng-controller="SnapshotModalCtrl" ng-show="false"></button>
                    <button id="volume_controller" ng-controller="VolumeModalCtrl" ng-show="false"></button>
                </div>
            </div>
            <div class="grid-body">
                <table id="volume_available_tb"></table>
            </div>
        </div>
        <div id="fake_deleted_list" style="display: none;">
            <div class="grid-tools">
            </div>
            <div class="grid-body">
                <table id="volume_fake_deleted_list"></table>
            </div>
        </div>
    </div>

    <!-- <div class="panel-body">
        <div class="title-tag">
            <h3>卷</h3>
            <p>卷管理</p>
        </div>
        <div class="grid-tools">
            <div class="grid-operate pull-left">
                <button id="snapshot_create" ng-controller="SnapshotModalCtrl" ng-show="false"></button>
                <button id="volume_controller" ng-controller="VolumeModalCtrl" ng-show="false"></button>
            </div>
        </div>
        <div class="grid-body" id="gridttt">
            <table id="volume_available_tb"></table>
        </div>
    </div> -->
</div>
